package apiTestBusiness;

import easyDAO.SqlDispatch;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.SqlReturnModel;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by yangxianming on 2017/9/30.
 */
public class AddApi implements TestServerBusinessImpl {

    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig){
        JSONObject returnJson = JSON.parseObject("{\"apistatus\":0,\"result\":\"\",\"errorMsg\":\"\"}");

        //读取请求json
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String requestInfo = "";

        try {
            inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null)
                requestInfo = requestInfo + line;
        }catch (Exception e){
            //请求流如果出现异常的时候
            returnJson.put("apistatus", "0");
            returnJson.put("errorMsg", e.getMessage());
            return returnJson.toString();
        }

        //解析json对象
        JSONObject apiJson = JSON.parseObject(requestInfo);
        SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
        SqlReturnModel sqlReturnModel = sqlDispatch.insert("testedapi", apiJson);

        String apistatus = (sqlReturnModel.getIsSuccess()) ? "1" : "0";
        returnJson.put("apistatus", apistatus);
        returnJson.put("errorMsg", sqlReturnModel.getFailingReason());

        return returnJson.toString();
    }
}
